<template>
  <app-main-wrapper>
    <page-title class="title" title='SHOP PAGE' subtitle='SHOP PAGE'
                :style='{background: "url(" + titleBackImg + ")"}'/>
    <div class="main-content">
      <el-row class="menu" :gutter="16">
        <el-col :span="6">
         <span class="show-list-count">
           显示 {{page * listSize - listSize + 1}}–{{page * listSize}} 共 {{total}} 个结果
         </span>
        </el-col>
        <el-col :span="3">
          <el-button class="btn-filter" type="text">
            <i class="fa fa-filter"/>
            过滤
            <i class="el-icon-arrow-down"/>
          </el-button>
        </el-col>
        <el-col :span="6" style="padding-top: 4px">
          <i class="fa fa-sort-amount-desc"/>
          <p class="p-sort-by">
            排序
          </p>
          <el-select class="sort-by-select myInput" size="small" v-model="sortBy" @change="orderChange">
            <el-option class="select-option" v-for="item in orders" :key="item" :label="item" :value="item">
              {{item}}
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="3">
          <ul class="list-col">
            <li><a @click="columnChange(4)">
              <!--suppress HtmlUnknownTarget -->
              <img :src="image.Grid4" alt="">
            </a></li>
            <li><a @click="columnChange(3)">
              <!--suppress HtmlUnknownTarget -->
              <img :src="image.Grid2" alt="">
            </a></li>
            <li><a @click="columnChange(2)">
              <!--suppress HtmlUnknownTarget -->
              <img :src="image.Grid1" alt="">
            </a></li>
          </ul>
        </el-col>
      </el-row>
      <el-row :gutter="40" class="content">
        <el-col :span="17" class="left">
          <!--suppress HtmlUnknownAttribute -->
          <div v-loading="goodsLoading" class="good-wrap">
            <el-row :gutter="32" class="goods" v-for="(row, index) in goodListRow" :key="index">
              <el-col class="box" :span="24 / columns" v-for="item in row" :key="item.id">
                <good-box2 class="item" :good="item" :max='10'
                           :size="columns >= 4 ? 'mini' : (columns >= 3 ? 'small' : 'default')"/>
              </el-col>
            </el-row>
          </div>
          <el-pagination class="pagination" @size-change="handleSizeChange"
                         @current-change='handleCurrentChange'
                         :page-size.sync='listSize' :page-sizes="pageSizes" :total.sync="total"
                         :current-page.sync="page" background :disabled="paginationDisabled"
                         layout="sizes, total, jumper, prev, pager, next" />
        </el-col>
        <el-col :span="7" class="right">
          <el-input class="myInput" placeholder="在此进行搜索" v-model="search2"
                    @keyup.enter.native="fnSearch" style="margin-bottom: 40px">
            <template slot="suffix">
              <el-button :disabled="loading" type="text" role="button" :loading="goodsLoading"
                         @click="fnSearch" style="margin-right: 8px;">
                <i class="el-icon-search" />
              </el-button>
            </template>
          </el-input>
          <span class="goodTitle">New Product</span>
          <!--suppress HtmlUnknownAttribute -->
          <div class="new-product-wrap" v-loading="newProductLoading">
            <el-carousel v-if="newProductList != null && newProductList.length > 0"
                         :height="(90 * rightPageSize + 10) + 'px'"
                         indicator-position="none" direction="vertical">
              <el-carousel-item v-for="(item1, index) in newProductPage" :key="index">
                <template v-for="(item2, index2) in item1">
                <el-row :gutter="32" :key="index+'-'+index2">
                  <el-col :span="24">
                    <good-box-simple class="good-box-simple" :id="item2.id" :image1="item2.image1"
                                     :image2="item2.image2" :title="item2.title" :price="item2.price"/>
                  </el-col>
                </el-row>
              </template>
              </el-carousel-item>
            </el-carousel>
          </div>
          <span class="goodTitle">Recent Review</span>
          <!--suppress HtmlUnknownAttribute -->
          <div class="recent-review-wrap" v-loading="recentReviewLoading">
            <el-carousel v-if="recentReviewList != null && recentReviewList.length > 0"
                         :height="(90 * rightPageSize + 10) + 'px'"
                         indicator-position="none" direction="vertical">
              <el-carousel-item v-for="(item1, index) in recentReviewPage" :key="index">
                <template v-for="(item2, index2) in item1">
                  <el-row :gutter="32" :key="index+'-'+index2">
                    <el-col :span="24">
                      <good-box-simple class="good-box-simple" :id="item2.id" :image1="item2.image1"
                                       :image2="item2.image2" :title="item2.title" :price="item2.price"/>
                    </el-col>
                  </el-row>
                </template>
              </el-carousel-item>
            </el-carousel>
          </div>
          <div class="filter-wrap">
            <good-box1 :id="12" class="rightGood" :image="ImageShopAdd" title="75% off" description="For Gents Wear" name="ddd"
              direction="left"/>
            <span class="goodTitle">Color</span>
          </div>
        </el-col>
      </el-row>
    </div>
  </app-main-wrapper>
</template>

<script>
import AppMainWrapper from '@/components/wrapper/AppMainWrapper'
import titleImg from '@img/page-titlebg.png'
import PageTitle from '@/views/part/index/PageTitle'
import Grid4 from '@/assets/img/icons/3grid.svg'
import Grid2 from '@/assets/img/icons/2grid.svg'
import Grid1 from '@/assets/img/icons/1grid.svg'
import GoodBox2 from '@/components/general/goods/GoodBox2'
import GoodBox1 from '@/components/general/goods/GoodBox1'
import product1 from '@img/product/product-1.jpg'
import GoodBoxSimple from '@/components/general/goods/GoodBoxSimple'
import ImageShopAdd from '@/assets/img/shop/shop-add.png'
import { queryGoodDetailByPage, queryNewProductsPage } from '@/api/ApiGoodDetail'
import { ResultCode } from '@/constants/constants'
import PageDTO from '@/api/entity/PageDTO'
import GoodDetailQueryDTO, { SearchTypeConstants } from '@/api/entity/GoodDetailQueryDTO'
export default {
  name: 'AppShopList',
  components: {
    GoodBoxSimple,
    GoodBox1,
    GoodBox2,
    PageTitle,
    AppMainWrapper },
  props: {
    search: {
      request: true,
      type: String
    },
    type: {
      request: true,
      type: String,
      validator: function (value) {
        return [SearchTypeConstants.SEARCH_TYPE_DEFAULT,
          SearchTypeConstants.SEARCH_TYPE_DEFAULT,
          SearchTypeConstants.SEARCH_TYPE_GOODS_NAME].indexOf(value) !== -1
      }
    }
  },
  data () {
    return {
      ImageShopAdd,
      goodsLoading: false,
      newProductLoading: false,
      recentReviewLoading: false,
      search2: '',
      image: {
        Grid4,
        Grid2,
        Grid1
      },
      sortBy: '默认',
      columns: 4,
      orders: [
        '默认',
        '新上架',
        '评分',
        '价格: 从低到高',
        '价格: 从高到低'
      ],
      pageSizes: [12, 24, 36, 48, 60],
      list: [],
      total: 0,
      listSize: 12,
      page: 1,
      newProductList: [],
      recentReviewList: [],
      titleBackImg: titleImg
    }
  },
  computed: {
    loading () {
      return this.goodsLoading
    },
    paginationDisabled () {
      return this.goodsLoading
    },
    /**
     * 对搜索的商品数据进行分行，便于循环
     */
    goodListRow () {
      const page = []
      let p = []
      const rowSize = this.columns
      for (let i = 0; i < this.list.length; i++) {
        p.push(this.list[i])
        if (p.length === rowSize) {
          page.push(p)
          p = []
        }
      }
      if (p.length !== 0) {
        page.push(p)
      }
      return page
    },
    /**
     * 根据pageSize自动适配右侧newProductList和recentReviewList的高度和每页个数
     */
    rightPageSize () {
      let size
      if (this.listSize < 24) {
        size = 3
      } else if (this.listSize < 36) {
        size = 4
      } else if (this.listSize < 48) {
        size = 6
      } else {
        size = 8
      }
      if (this.columns === 3) {
        size += Math.floor(size / 2)
      }
      if (this.columns === 2) {
        size += size
      }
      return size
    },
    /**
     * 对newProductList分页，方便for循环
     */
    newProductPage () {
      const page = []
      let p = []
      const pageSize = this.rightPageSize
      for (let i = 0; i < this.newProductList.length; i++) {
        p.push(this.newProductList[i])
        if (p.length === pageSize) {
          page.push(p)
          p = []
        }
      }
      if (p.length !== 0) {
        page.push(p)
      }
      return page
    },
    /**
     * 对recentReviewList分页，方便for循环
     */
    recentReviewPage () {
      const page = []
      let p = []
      const pageSize = this.rightPageSize
      for (let i = 0; i < this.recentReviewList.length; i++) {
        p.push(this.recentReviewList[i])
        if (p.length === pageSize) {
          page.push(p)
          p = []
        }
      }
      if (p.length !== 0) {
        page.push(p)
      }
      return page
    }
  },
  methods: {
    /**
     * 排序改变，刷新列表
     * @param change 排序名称
     */
    orderChange (change) {
      this.freshList()
    },
    /**
     * 显示列数改变
     * @param col 列数
     */
    columnChange (col) {
      this.columns = col
    },
    /**
     * 每页显示数据改变
     */
    handleSizeChange () {
      this.freshList()
    },
    /**
     * 当前页面改变
     */
    handleCurrentChange () {
      this.freshList()
    },
    convertDetailToItem (detail) {
      const item = {}
      item.id = detail.id
      item.title = detail.name
      item.hot = detail.score
      if (detail['subGoodList'] && typeof detail['subGoodList'] === 'object') {
        detail['subGoodList'].forEach((sub, index) => {
          if (index === 0) {
            item.price = sub.price
          }
          if (item.price > sub.price) {
            item.price = sub.price
          }
        })
      }
      const pictures = detail['goodPictureList']
      if (pictures && typeof pictures === 'object') {
        if (pictures.length === 0) {
          item.view1 = product1
          item.view2 = product1
        }
        if (pictures.length === 1) {
          item.view1 = pictures[0].image
          item.view2 = pictures[0].image
        }
        if (pictures.length > 1) {
          item.view1 = pictures[0].image
          item.view2 = pictures[1].image
        }
      }
      return item
    },
    /**
     * 查询商品数据
     */
    freshList () {
      const vm = this
      vm.goodsLoading = true
      const pageDTO = PageDTO.instance()
      pageDTO.setSize(this.listSize)
      pageDTO.setCurrent(this.page)
      const condition = GoodDetailQueryDTO.instance()
      condition.addSearch(this.search)
      condition.setSearchType(this.type)
      pageDTO.setCondition(condition)
      queryGoodDetailByPage(pageDTO, data => {
        if (data && data.code === ResultCode.OK) {
          this.total = data.object.total
          const goodsData = data.object['records']
          const list = []
          goodsData.forEach(item => {
            list.push(this.convertDetailToItem(item))
          })
          this.list = list
        }
      }, () => {
        vm.goodsLoading = false
      })
    },
    convertDetailToItem2 (detail) {
      const item = {}
      item.id = detail.id
      item.title = detail.name
      item.hot = detail.score
      if (detail['subGoodList'] && typeof detail['subGoodList'] === 'object') {
        detail['subGoodList'].forEach((sub, index) => {
          if (index === 0) {
            item.price = sub.price
          }
          if (item.price > sub.price) {
            item.price = sub.price
          }
        })
      }
      const pictures = detail['goodPictureList']
      if (pictures && typeof pictures === 'object') {
        if (pictures.length === 0) {
          item.image1 = product1
          item.image2 = product1
        }
        if (pictures.length === 1) {
          item.image1 = pictures[0].image
          item.image2 = pictures[0].image
        }
        if (pictures.length > 1) {
          item.image1 = pictures[0].image
          item.image2 = pictures[1].image
        }
      }
      return item
    },
    /**
     * 更新NewProduct列表
     */
    freshNewProduct () {
      const vm = this
      vm.newProductLoading = true
      queryNewProductsPage(1, 24, data => {
        if (data && data.code === ResultCode.OK) {
          const goodsData = data.object['records']
          const list = []
          goodsData.forEach(item => {
            list.push(this.convertDetailToItem2(item))
          })
          vm.newProductList = list
        }
      }, () => {
        vm.newProductLoading = false
      })
    },
    /**
     * 更新recentReview列表
     */
    freshRecentReview () {
      const vm = this
      vm.recentReviewLoading = true
      queryNewProductsPage(1, 24, data => {
        if (data && data.code === ResultCode.OK) {
          const goodsData = data.object['records']
          const list = []
          goodsData.forEach(item => {
            list.push(this.convertDetailToItem2(item))
          })
          vm.recentReviewList = list
        }
      }, () => {
        vm.recentReviewLoading = false
      })
    },
    /**
     * 搜索商品
     */
    fnSearch () {
      if (this.search2 && this.search2.trim().length > 0) {
        const searchStr = this.search2.trim()
        this.$router.push('/shopList/default/' + searchStr)
      }
    }
  },
  /**
   * 加载后获取数据
   */
  mounted () {
    this.freshList()
    this.freshNewProduct()
    this.freshRecentReview()
  },
  watch: {
    /**
     * 刷新页面，重新搜索商品
     */
    search (val) {
      this.search2 = val
      this.freshList()
    }
  }
}
</script>

<style lang="scss" scoped>

  .title{
    width: 100%;
    height: 180px;
    user-select: none;
    padding: 54px 220px;
    letter-spacing: -1px;
  }

  .main-content{
    max-width: 1110px;
    width: 100%;
    margin: 80px auto;

    .menu{

      font-size: 16px;
      height: 40px;
      text-align: left;

      .show-list-count{
        user-select: none;
        height: 100%;
        line-height: 40px;
      }

      .sort{

      }

      .p-sort-by{
        color: #999999;
        display: inline;
        margin-left: 4px;
        font-size: 14px;
        line-height: 16px;
        user-select: none;
      }

      .sort-by-select{
        width: 160px;
        margin-left: 6px;
        user-select: none;

        .select-option{
          user-select: none;
        }

      }

      .btn-filter, .btn-sort{
        color: #555555;
      }

      .btn-filter:hover, .btn-sort:hover{
        color: #333333;
      }

      .list-col{
        display: block;
        list-style: none;
        white-space: nowrap;
        overflow-x: visible;
        height: 100%;
        padding-top: 2px;

        li{
          display: inline-block;
          width: 18px;
          height: 18px;
          margin: 8px 6px;
          cursor: pointer;
          vertical-align: middle;

          img{
            width: 100%;
            height: 100%;
            vertical-align: middle;
          }

        }

      }

    }

    .content{
      margin-top: 30px;

      .left{
        transition: .8s;

        .good-wrap{
          min-height: 60px;
          margin-bottom: 20px;
          .goods{

            .box{
              margin-bottom: 35px;

              .item{
                margin: auto;
              }

            }

          }
        }

      }

      .right{

        .good-box-simple{
          transform: scale(0.9);
          margin: -12px -14px;
        }

        .goodTitle{
          display: block;
          text-align: left;
          font-size: 20px;
          color: #333333;
          font-weight: 700;
          margin: 10px 0;
        }

        .new-product-wrap{
          min-height: 310px;
        }

        .recent-review-wrap{
          min-height: 310px;
        }

        .filter-wrap{

          .rightGood{
            margin: 32px 24px 32px -14px;
            transform: scale(0.9)
          }

        }
      }

    }

  }

</style>
